package top.hserver.gateway.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.beetl.sql.core.engine.PageQuery;
import top.hserver.core.ioc.annotation.Autowired;
import top.hserver.core.ioc.annotation.Bean;
import top.hserver.gateway.dao.GatewayNodeDao;
import top.hserver.gateway.dao.GatewayRouterNodeDao;
import top.hserver.gateway.entity.GateWayNode;
import top.hserver.gateway.entity.GateWayRouterNode;
import top.hserver.gateway.service.GatewayNodeService;
import top.hserver.gateway.utils.UUIDUtil;

import java.util.List;

/**
 * @author hxm
 */

@Slf4j
@Bean
public class GatewayNodeServiceImpl implements GatewayNodeService {

    @Autowired
    private GatewayNodeDao gatewayNodeDao;

    @Autowired
    private GatewayRouterNodeDao gatewayRouterNodeDao;

    @Override
    public boolean add(GateWayNode gateWayNode) {
        try {
            if (gateWayNode.getIp() == null || gateWayNode.getPort() == null) {
                return false;
            }
            gateWayNode.setId(UUIDUtil.randomUUID32());
            gatewayNodeDao.insert(gateWayNode);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    @Override
    public PageQuery<GateWayNode> list(Long page,Long pageSize) {
        PageQuery<GateWayNode> pages = gatewayNodeDao.createLambdaQuery().page(page, pageSize);
        return pages;
    }

  @Override
  public List<GateWayNode> all() {
      return gatewayNodeDao.all();
  }

  @Override
    public boolean update(GateWayNode gateWayNode) {
        try {
            if (gateWayNode.getId() == null || gateWayNode.getIp() == null || gateWayNode.getPort() == null) {
                return false;
            }
            gatewayNodeDao.updateById(gateWayNode);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public boolean remove(String id) {
        try {
            if (id == null) {
                return false;
            }
            gatewayRouterNodeDao.createLambdaQuery().andEq(GateWayRouterNode::getNodeId,id).delete();
            gatewayNodeDao.deleteById(id);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
